package com.example.h264rtp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramSocket;

import com.rtp.DataFrame;
import com.rtp.Participant;
import com.rtp.RTPAppIntf;
import com.rtp.RTPSession;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity implements RTPAppIntf {
	
	private final String SERVER_IP = "192.168.1.32";
	private final int SERVER_PORT = 9090;
	private RTPSession mRtpSession;

	DatagramSocket mRtpSocket = null;
	DatagramSocket mRtcpSocket = null;
	private final int PORT = 8888;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						initRTPSession();
						send();
					}
				}).start();
			}
		});
	}
	
	private void send() {
		FileInputStream fis = null;
		try {
			// 码流文件
			File file = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/111111/tt.h264");
			fis = new FileInputStream(file);
			
			int nLen = 0;
			byte[] buff = new byte[1024*2];
			while((nLen = fis.read(buff)) > 0){
            	if(mRtpSession != null) {
            		Log.d("ktian", "nLen -->"+nLen);
            		byte[] temp = new byte[nLen];
            		System.arraycopy(buff, 0, temp, 0, nLen);
            		mRtpSession.sendData(temp);
            	}
            }
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	private void initRTPSession() {
		
		try {
			mRtpSocket = new DatagramSocket(PORT);
			mRtcpSocket = new DatagramSocket(PORT+1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		mRtpSession = new RTPSession(mRtpSocket, mRtcpSocket);
		mRtpSession.RTPSessionRegister(this, null, null);
		
		Participant p = new Participant(SERVER_IP, SERVER_PORT, SERVER_PORT+1);
		mRtpSession.addParticipant(p);
	}

	
	
	////////////////////////////////////RTP///////////////////////////////////
	@Override
	public void receiveData(DataFrame frame, Participant p) {
		String s = new String(frame.getConcatenatedData());
		Log.d("ktian", "The Data has been received: "+ s +" , thank you " + p.getCNAME()+"("+p.getSSRC()+")");
	}

	@Override
	public void userEvent(int type, Participant[] participant) {
		// Do nothing
	}

	@Override
	public int frameSize(int payloadType) {
		return 1;
	}
	
	
	

}
